# -*- coding:UTF-8 -*-
import json
import os, shutil
import requests
from mutagen.id3 import ID3, APIC, TIT2, TPE1, TALB


def SetMp3Info(path, info):
    songFile = ID3(path)
    songFile['APIC'] = APIC(  # 插入封面
        encoding=3,
        mime='image/jpeg',
        type=3,
        desc=u'Cover',
        data=info['picData']
    )
    songFile['TIT2'] = TIT2(  # 插入歌名
        encoding=3,
        text=info['title']
    )
    songFile['TPE1'] = TPE1(  # 插入第一演奏家、歌手、等
        encoding=3,
        text=info['artist']
    )
    # songFile['TALB'] = TALB(  # 插入专辑名
    #     encoding=3,
    #     text=info['album']
    # )
    songFile.save()


if __name__ == '__main__':
    # 创建存储mp3的文件夹
    baseDir = os.path.dirname(__file__) + '/musics'
    if not os.path.exists(baseDir):
        os.mkdir(baseDir)
    resourceFileDir = os.path.dirname(__file__) + '/mp3List'
    for home, dirs, files in os.walk(resourceFileDir):
        for filename in files:
            resourceFile = home + '/' + filename
            with open(resourceFile, 'r', encoding='utf8')as fp:
                musics = json.load(fp)
            for music in musics['data']['list']:
                musicName = music['name'] + '-' + music['artist']
                print("开始下载: " + musicName)
                print("......")
                # musicDir = baseDir + '/' + musicName
                # 下载所有MP3至musics目录
                musicDir = baseDir
                if not os.path.exists(musicDir):
                    os.mkdir(musicDir)
                try:
                    if music.get('cover') is not None:
                        with open(musicDir + '/' + musicName + '.jpg', 'wb') as f:
                            f.write(requests.get(music['cover']).content)
                    if music.get('lrc') is not None:
                        with open(musicDir + '/' + musicName + '.lrc', 'wb') as f:
                            f.write(requests.get(music['lrc']).content)
                    if music.get('url_320') is not None:
                        with open(musicDir + '/' + musicName + '.mp3', 'wb') as f:
                            f.write(requests.get(music['url_320']).content)

                    picPath = musicDir + '/' + musicName + '.jpg'
                    with open(picPath, 'rb') as f:
                        picData = f.read()
                    info = {'picData': picData, 'title': musicName,
                            'artist': music['artist']}
                    songPath = musicDir + '/' + musicName + '.mp3'
                    SetMp3Info(songPath, info)
                    print(musicName + ' 下载成功!')
                except OSError as e:
                    print(e)
                    print(musicName + ' 下载失败！')
                    pass

            downloadOverDir = resourceFileDir + '/downloadOver'
            if not os.path.exists(downloadOverDir):
                os.mkdir(downloadOverDir)
            downloadOverFile = downloadOverDir + '/' + filename
            shutil.move(resourceFile, downloadOverFile)
            print('移动资源文件至已下载目录=============>')

